<template>
    <!-- 查询 -->
    <el-form :inline="true" :model="queryData">
      <template v-for="item in queryConfig" :key="item.id">
        <!-- 输入框 -->
        <el-form-item v-if="!item.type || item.type == 'text'" :label="item.label">
          <el-input v-model="queryData[item.field]" :placeholder="'请输入' + item.label" />
        </el-form-item>
      </template>
  
      <!-- 按钮 -->
      <template v-if="queryConfig.length">
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getData">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="" :icon="RefreshRight" @click="reset">重置</el-button>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" :icon="Plus" @click="add">新增</el-button>
      </el-form-item>
    </el-form>
  
    <!-- 表格 -->
    <el-table :data="tableData" v-loading="loading" height="calc(100vh - 85px)" table-layout="auto" stripe>
      <template v-for="item in props.config.data" :key="item.id">
        <!-- 字典 -->
  
        <el-table-column v-if="item.type == 'select'" :label="item.label">
          <template #default="scope">
            <template v-for="opt in item.options">
              <template v-if="scope.row[item.field] == opt.value">{{
      opt.label
    }}</template>
            </template>
          </template>
        </el-table-column>
  
        <!-- 图片 -->
        <el-table-column v-else-if="item.type == 'image'" :label="item.label">
          <template #default="scope">
            <div v-if="scope.row[item.field].length != 0"> 
            <!-- <el-image style="width: 80px; height: 80px" :src="baseURL + scope.row[item.prop]" fit="contain" /> -->
            <img v-for="(item, index) in scope.row[item.field]" :key="index" style="width: 80px; height: 80px" :src="item" />
          </div>
          <div v-else>无图片</div>
          </template>
        </el-table-column>
  
        <!-- 默认 -->
        <el-table-column v-else :prop="item.field" :label="item.label">
          <template #default="scope">
            <div v-html="scope.row[item.field]" class="aaa"></div>
          </template>
        </el-table-column>
      </template>
  
      <el-table-column v-if="props.config.API.edit || props.config.API.del" fixed="right" label="操作" width="140">
        <template #default="scope">
          <el-button v-if="props.config.API.edit" link type="primary" size="small" :icon="Edit"
            @click="edit(scope.row)">编辑</el-button>
          <el-popconfirm v-if="props.config.API.del" title="确认删除此项?" confirm-button-text="确认" cancel-button-text="取消"
            @confirm="del(scope.row.id)">
            <template #reference>
              <el-button link type="danger" size="small" :icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  
    <el-pagination background layout="prev, pager, next" :total="count" @change="pageChange" />
  
    <!-- 表单 -->
    <el-dialog v-model="visible" :title="formData.id ? '编辑': '新增'" width="600" @close="close">
      <el-form :model="formData" ref="formRef" :rules="rules">
        <template v-if="formData.id">
        <template v-for="item in formConfig" :key="item.id" >
          <!-- 文本 -->
          <el-form-item v-if="!item.type || item.type == 'text'" :label="item.label" :prop="item.field"
            :label-width="labelWidth">
            <el-input v-model="formData[item.field]" :placeholder="'请输入' + item.label" clearable />
          </el-form-item>
  
          <!-- 文本域 -->
          <el-form-item v-if="item.type == 'textarea'" :label="item.label" :prop="item.field" :label-width="labelWidth">
            <el-input v-model="formData[item.field]" :rows="2" type="textarea" :placeholder="'请输入' + item.label"
              clearable />
          </el-form-item>
  
          <!-- 密码框 -->
          <el-form-item v-if="item.type == 'password'" :label="item.label" :prop="item.field" :label-width="labelWidth">
            <el-input v-model="formData[item.field]" :placeholder="'请输入' + item.label" show-password clearable />
          </el-form-item>
  
          <!-- 选择 -->
          <el-form-item v-if="item.type == 'select'" :label="item.label" :prop="item.field" :label-width="labelWidth">
            <el-select v-model="formData[item.field]" :placeholder="'请选择' + item.label" style="width: 240px">
              <el-option v-for="item in item.options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
  
          <!-- 数字框 -- 月份-->
          <el-form-item v-if="item.type == 'number' && item.field == 'count'" :label="item.label" :prop="item.field"
            :label-width="labelWidth">
            <el-input-number v-model="formData[item.field]" :precision="item.precision || 0" :min="1" />
          </el-form-item>
  
          <!-- 价格 -->
          <el-form-item v-if="item.type == 'number' && item.field == 'price'" :label="item.label" :prop="item.field"
            :label-width="labelWidth">
            <!-- <el-input-number v-model="formData[item.field]" :precision="item.precision || 0" /> -->
            <el-input-number v-model="formData[item.field]" :precision="item.precision || 2" :min="0" :step="0.01" />
          </el-form-item>
  
          <!-- 上传 -->
          <el-form-item v-if="item.type == 'image'" :label="item.label" :label-width="labelWidth">
            <!-- <upload
                  ref="theDramaWasReleasedRef"
                  flags="1"
                  class="theDramaWasReleasedClass"
                  title="添加图片"
                  prompt="图片"
                  :format="format"
                ></upload> -->
            <el-upload class="avatar-uploader" :on-preview="handlePictureCardPreview" list-type="picture-card"   v-model:file-list="successImg"  :action="uploadURL" multiple  name="file" accept="image/*"
              :on-success="success">
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <!-- 富文本 -->
          <el-form-item v-if="item.type == 'editor'" type="number" :label="item.label" :prop="item.field"
            :label-width="labelWidth">
            <Editor :value="content" @updateValue="getMsg" />
          </el-form-item>
        </template>
      </template>
      <template v-if="!formData.id">
        <template v-for="item in addFormData" :key="item.id" >
          <!-- 文本 -->
          <el-form-item v-if="!item.type || item.type == 'text'" :label="item.label" :prop="item.field"
            :label-width="labelWidth">
            <el-input v-model="formData[item.field]" :placeholder="'请输入' + item.label" clearable />
          </el-form-item>
  
          <!-- 文本域 -->
          <el-form-item v-if="item.type == 'textarea'" :label="item.label" :prop="item.field" :label-width="labelWidth">
            <el-input v-model="formData[item.field]" :rows="2" type="textarea" :placeholder="'请输入' + item.label"
              clearable />
          </el-form-item>
  
          <!-- 密码框 -->
          <el-form-item v-if="item.type == 'password'" :label="item.label" :prop="item.field" :label-width="labelWidth">
            <el-input v-model="formData[item.field]" :placeholder="'请输入' + item.label" show-password clearable />
          </el-form-item>
  
          <!-- 选择 -->
          <el-form-item v-if="item.type == 'select'" :label="item.label" :prop="item.field" :label-width="labelWidth">
            <el-select v-model="formData[item.field]" :placeholder="'请选择' + item.label" style="width: 240px">
              <el-option v-for="item in optionData" :key="item.id" :label="item.company_name" :value="item.id" />
            </el-select>
          </el-form-item>
  
          <!-- 数字框 -- 月份-->
          <el-form-item v-if="item.type == 'number' && item.field == 'count'" :label="item.label" :prop="item.field"
            :label-width="labelWidth">
            <el-input-number v-model="formData[item.field]" :precision="item.precision || 0" :min="1" />
          </el-form-item>
  
          <!-- 价格 -->
          <el-form-item v-if="item.type == 'number' && item.field == 'price'" :label="item.label" :prop="item.field"
            :label-width="labelWidth">
            <!-- <el-input-number v-model="formData[item.field]" :precision="item.precision || 0" /> -->
            <el-input-number v-model="formData[item.field]" :precision="item.precision || 2" :min="0" :step="0.01" />
          </el-form-item>
  
          <!-- 上传 -->
          <el-form-item v-if="item.type == 'image'" :label="item.label" :label-width="labelWidth">
            <!-- <upload
                  ref="theDramaWasReleasedRef"
                  flags="1"
                  class="theDramaWasReleasedClass"
                  title="添加图片"
                  prompt="图片"
                  :format="format"
                ></upload> -->
            <el-upload class="avatar-uploader" :on-preview="handlePictureCardPreview" list-type="picture-card"   v-model:file-list="successImg"  :action="uploadURL" multiple  name="file" accept="image/*"
              :on-success="success">
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <!-- 富文本 -->
          <el-form-item v-if="item.type == 'editor'" type="number" :label="item.label" :prop="item.field"
            :label-width="labelWidth">
            <Editor :value="content" @updateValue="getMsg" />
          </el-form-item>
        </template>
      </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">关闭</el-button>
          <el-button type="primary" @click="submit(formRef)"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  
    <!-- <Pagination :total="total" @changeSize="handlerChangeSize" @changeCurrent="handlerChangeCurrent" /> -->
    <el-dialog v-model="dialogVisible">
      <div style="text-align: center">
    <img w-full style="max-width: 500px;" :src="dialogImageUrl" alt="Preview Image" />
  </div>
  </el-dialog>
  </template>
  
  <script setup>
  import upload from "@/components/upload.vue";
  import { ref, defineProps, reactive } from "vue";
  import {
    Search,
    RefreshRight,
    Plus,
    Edit,
    Delete,
  } from "@element-plus/icons-vue";
  import { ElMessage } from "element-plus";
  import { baseURL, uploadURL } from "@/api/config.json";
  import Editor from "@/components/Editor/index.vue";
  import Pagination from "@/components/Pagination.vue";
  
  const props = defineProps({
    config: {
      type: Object,
      default: () => {
        return {
          API: {
            get: Promise.resolve(),
            add: Promise.resolve(),
            edit: Promise.resolve(),
            del: Promise.resolve(),
            listApi: Promise.resolve(),
          },
          data: [],
        };
      },
    },
  });
  let optionData = []
  const getDataTwo = () => {
  if (!props.config.API.listApi) return console.log("required API.get method");
  let token = localStorage.getItem("token");
  const queryParams = Object.assign( { user_token: token });

  props.config.API.listApi(queryParams)?.then((res) => {
    console.log( res.data.items)
    optionData = res.data.items;
  });
};
getDataTwo()
  const close = () => {
    formData.value =  ref({});
    successImg = []
    console.log(formData.value);
  }
  const dialogImageUrl = ref(null);
  const dialogVisible = ref(false);
  const additionalData = {
    user_token: 'value1',
        // 可以添加更多参数
      }
      const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
  let successImg = []
      additionalData.user_token = localStorage.getItem("token");
   const format =  ["jpg", "png", "JPG", "PNG", "jpeg", "JPEG", "bmp", "BMP"]
  const total = ref(75);
  const handlerChangeSize = (size) => {
    queryData.pageSize = size;
    getData();
  };
  const handlerChangeCurrent = (num) => {
    queryData.pageNum = num;
    getData();
  };
  let num = 0
  const success = (res) => {
    console.log(res)
    if (num == 1) {
      successImg.push({url: res.data.download_url})
    }
    num++
    if (num == 1) {
      num = 0
    }
    console.log(res, successImg)
  }
  const notice_board  = ref();
  const getMsg = (val) => {
    formData.value.notice_board  = val;
  };
  const labelWidth = 180;
  const clear = (obj) => {
    for (const key in obj) {
      queryData[key] = "";
    }
  };
  
  // 查询
  const queryData = reactive({
    pageSize: 10,
    pageNum: 1,
  });
  const queryConfig = ref(props.config.data.filter((i) => i.query));
  const reset = () => {
    clear(queryData);
    getData();
  };
  
  // 列表
  const page = ref(1);
  const count = ref();
  const loading = ref(false);
  const tableData = ref([]);
  const getData = () => {
    if (!props.config.API.get) return console.log("required API.get method");
    loading.value = true;
    let token = localStorage.getItem("token");
    const queryParams = Object.assign(queryData, { user_token: token });
  
    props.config.API.get(queryParams)?.then((res) => {
      console.log(res)
      tableData.value = res.data.items
      loading.value = false;
    });
  };
  getData();
  
  const pageChange = (currentPage) => {
    page.value = currentPage;
    getData();
  };
  
  // 新增/编辑
  const visible = ref(false);
  const formRef = ref();
  const formData = ref({});
  const addFormData = ref([
  {
            field: "logistics_company",
            label: "物流所属公司",
            type: 'select',
            required: true
        },
  {
            field: "logistics_number",
            label: "物流号",
            required: true
        },
  {
            field: "commodity_name",
            label: "商品名称",
            required: true
        },
  {
            field: "theory_count",
            label: "理论数量",
            required: true
        },
  {
            field: "commodity_images",
            label: "图片列表",
            type: 'image',
            required: true
        },
  ]);
  const formConfig = ref(props.config.data.filter((i) => i.operate));
  const rules = ref({});
  props.config.data.map((item) => {
    if (item.required) {
      rules.value[item.field] = [
        {
          required: true,
          message: `${item.type == "select" ? "请选择" : "请输入"}${item.label}`,
          trigger: "blur",
        },
      ];
    }
  });
  
  const add = () => {
    clear(formData.value);
    visible.value = true;
  };
  
  const edit = (row) => {
    try {
      console.log(row.notice_board , "123");
    notice_board .value = row.content;
    formData.value = { ...row };
    console.log()
    if (row.commodity_images.length != 0) {
      let arr = JSON.parse(JSON.stringify(row.commodity_images))
      arr.forEach((item) => {
        successImg.push({url:item})
      })
    }
    formData.value.commodity_id = row.id
    // formData.value.commodity_images = row.commodity_images.toString()
    } catch (error) {
      console.log(error)
    }
    
    
    visible.value = true;
  };
  
  const submit = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
      if (valid) {
        const data = { ...formData.value };
        let token = localStorage.getItem("token");
        data.user_token = token;
        let arr = []
        successImg.forEach((itme) => {
          arr.push(itme.url)
          // itme =  `"${ itme.url  }"`
        })
        console.log(arr)
        data.commodity_images = arr
//         const str = data.commodity_images
// const regex = new RegExp("\", "g");
// const replacement = "替换后的文本";
// const result = str.replace(regex, replacement);
        const API = data.id ? props.config.API.edit : props.config.API.add;
        data.vip_id = data.id;
        API(data).then((res) => {
          if (res.code == 0) {
            visible.value = false;
            ElMessage.success("操作成功");
            getData();
          } else {
            ElMessage.error(res.msg);
          }
        });
      }
    });
  };
  
  // 删除
  const del = (id) => {
    let token = localStorage.getItem("token");
    props.config.API.del({ vip_id: id, user_token: token }).then(
      (res) => {
        if (res.code == 0) {
          ElMessage.success("删除成功");
          getData();
        } else {
          ElMessage.error(res.msg);
        }
      }
    );
  };
  </script>
  <style scoped lang="scss">
  .theDramaWasReleasedClass {
  margin-top: 10px;
  ::v-deep {
    .upload-img {
      width: 180px;
      background-color: rgba(245, 245, 245, 1);
    }
    .upload-img .plusIcon {
      margin-top: 40px;
    }
  }
}
  .el-pagination {
    margin-top: 18px;
    justify-content: flex-end;
  }
  
  :deep(.cell img) {
    width: 50px !important;
    height: 50px !important;
  }
  
  :deep(.avatar-uploader .avatar) {
    width: 120px;
    height: 120px;
    display: block;
  }
  
  :deep(.avatar-uploader .el-upload) {
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: 0.2s;
  }
  
  :deep(.avatar-uploader .el-upload:hover) {
    border-color: #409eff;
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
  }
  </style>